import React from 'react';
import Api from 'Utils/api';
import { Modal, message } from 'antd';
import { WEBRTC_APPID } from 'Constants/config';
import './video.scss';


export default class OnAudioModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      isRecording: true,
      currentVolume: 1,
      loading: false,
      againRecord: false,
      isUsingPlugin: true,
      recordUrl: ''
    };
    this.handleStart = ::this.handleStart;
    this.handleStop = ::this.handleStop;
    this.handleAudio = ::this.handleAudio;
    this.initUserInfo = ::this.initUserInfo;
    this.connectChannel = ::this.connectChannel;
    this.changeBtnState = ::this.changeBtnState;
  }

  showModal() {
    this.setState({
      visible: true,
      loading: false,
      isRecording: true,
      againRecord: false,
      currentVolume: 1,
      recordUrl: ''
    }, () => {
      const self = this;
      AdapterJS.webRTCReady((isUsingPlugin) => {
        self.setState({
          isUsingPlugin
        });
      });
      this.initUserInfo();
    });
  }

  initUserInfo() {
    const api = new Api({
      method: 'POST',
      path: '/login/guest',
      success: (res) => {
        console.log(res);
        this.setState({
          userInfo: res
        }, () => {
          this.websocketConnect(res);
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  websocketConnect(userInfo) {
    const socket = new SockJS(`${window.config.API_HOST}/gs-guide-websocket?socket_auth=${userInfo.socket_auth}`);
    this.stompClient = Stomp.over(socket);
    this.stompClient.connect({}, () => {
      this.stompClient.subscribe(`/topic/guest.${userInfo.id}/chat`, (res) => {
        const json = JSON.parse(res.body);
        console.log('json', json);
        // 录制
        if (json.type === 'initRecordingRes') {
          this.setState({
            channelKey: json.channelKey,
            chatId: json.chatId,
            againRecord: true
          });
        }
        // 结束录制
        if (json.type === 'record_success') {
          this.setState({
            recordUrl: json.id,
            againRecord: true,
            loading: false,
          });
        }
      });
      console.log('send');
      this.stompClient.send('/app/recording/req', {}, JSON.stringify({ audioOnly: true }));
    });
  }
  connectChannel(channelkey, chatId) {
    console.log('connectChannel', channelkey, chatId, this.state.userInfo.id);
    const self = this;
    this.client = AgoraRTC.createClient({ mode: 'interop' });
    this.client.init(WEBRTC_APPID,
      () => {
        //加入 AgoraRTC 频道(join)
        this.client.join(channelkey, chatId, this.state.userInfo.id,
          () => {
            //创建音视频对象
            this.localStream = AgoraRTC.createStream({
              streamID: parseInt(this.state.userInfo.id, 10),
              audio: true,
              video: false,
              screen: false,
            });
            // 初始化音视频流对象
            this.localStream.init(() => {
              // 播放本地视频流
              window.stream = this.localStream.stream;
              console.log('enter');
              if (this.state.isUsingPlugin) {
                AdapterJS.attachMediaStream(document.getElementById('audio'), window.stream);
              } else {
                this.localStream.play('audio', '/images');
              }
              console.log('end');
              // 将本地的视频流上传到服务器
              this.client.publish(this.localStream, (err) => {
                console.log('publish is err', err);
              });
              // start record
              console.log('enterChannel');
              this.stompClient.send('/app/recording/start', {},
                JSON.stringify({ chatId: chatId, audioOnly: true }));
            }, () => {
              // console.log(err);
            });
          },
          () => {});
        self.changeBtnState();
      },
      (err) => { console.log(err); });
  }
  handOk() {
    const { recordUrl, againRecord, isRecording } = this.state;
    const { onOk } = this.props;
    if (!isRecording) {
      message.warn('请停止录制!', 3);
      return;
    }
    if (!recordUrl && againRecord) {
      return;
    }
    this.setState({
      visible: false,
    }, onOk && onOk(recordUrl));
  }

  close() {
    this.setState({
      visible: false,
    });
  }
  handleStart() {
    console.log('start');
    const { channelKey, chatId } = this.state;
    if (channelKey && chatId) {
      this.connectChannel(this.state.channelKey, this.state.chatId);
    }
  }
  handleStop() {
    this.client.leave((success) => { console.log(success); }, (err) => { console.log(err); });
    console.log('leave');
    this.client.unpublish(this.localStream);
    this.localStream.close();
    if (this.state.isUsingPlugin) {
      AdapterJS.attachMediaStream(document.getElementById('audio'), null);
    } else {
      this.localStream.stop();
    }
  }
  handleAudio() {
    const { againRecord, isRecording } = this.state;
    if (againRecord) {
      if (isRecording) {
        this.handleStart();
      } else {
        this.handleStop();
        this.setState({
          againRecord: false,
          loading: true,
        });
        this.changeBtnState();
        console.log('end');
      }
    }
  }
  changeBtnState() {
    this.setState(preState => ({
      isRecording: !preState.isRecording
    }), () => {
      clearInterval(this.timer);
      if (!this.state.isRecording) {
        this.timer = setInterval(() => {
          const newVolume = this.state.currentVolume === 6 ? 1 : this.state.currentVolume + 1;
          this.setState({
            currentVolume: newVolume
          });
        }, 500);
      }
    });
  }

  render() {
    const { loading, isRecording, isUsingPlugin } = this.state;
    const btnImg = isRecording ? 'icon_audio_record.png' : 'icon_audio_pause.png';
    return (
      <div>
        <Modal
          className="add-audio-modal"
          title="录制音频"
          visible={this.state.visible}
          onOk={this.handOk.bind(this)}
          onCancel={() => {
            this.close();
          }}
          confirmLoading={loading}
          maskClosable={false}
        >
          <div className="modal-audio-wrap">
            <div className="record-wrap">
              {
                isUsingPlugin ? <video id="audio" style={{ width: '100%', height: '100%' }} />
                  : <div id="audio" style={{ width: '100%', height: '100%' }} />
              }
            </div>
            <div className="volumu-wrap"><img src={`images/icons/icon_audio${this.state.currentVolume}.png`} alt="音量" /></div>
            <div className="audio-btn"><img src={`images/icons/${btnImg}`} alt="按钮" onClick={this.handleAudio.bind(this)} /></div>
          </div>
        </Modal>
      </div>
    );
  }
}
